"""
设置模块：处理用户设置相关的功能
包括Cookie管理、用户信息验证等
"""

import aiohttp
from fastapi import HTTPException
from fastapi.responses import JSONResponse
from bbdown.core.config import Config

async def verify_cookie(cookie: str) -> dict:
    """
    验证cookie是否有效
    
    参数：
        cookie (str): 用户提供的cookie字符串
        
    返回：
        dict: 包含验证结果和用户信息的字典
        
    异常：
        HTTPException: 当cookie无效或验证失败时抛出
    """
    try:
        async with aiohttp.ClientSession() as session:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Cookie': cookie
            }
            # 访问用户信息API来验证cookie
            async with session.get('https://api.bilibili.com/x/web-interface/nav', headers=headers) as response:
                if response.status != 200:
                    raise HTTPException(status_code=400, detail="Cookie无效，请检查后重试")
                
                data = await response.json()
                if data['code'] != 0:
                    raise HTTPException(status_code=400, detail="Cookie无效，请检查后重试")
                
                # 获取用户信息
                user_info = data['data']
                if not user_info['isLogin']:
                    raise HTTPException(status_code=400, detail="Cookie已失效，请重新登录")
                
                return {
                    "status": "success",
                    "message": "Cookie设置成功",
                    "user_info": {
                        "username": user_info['uname'],
                        "uid": user_info['mid']
                    }
                }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"设置Cookie失败: {str(e)}")

async def check_cookie_status() -> dict:
    """
    检查当前保存的cookie状态
    
    返回：
        dict: 包含cookie状态和用户信息的字典
    """
    try:
        config = Config()
        cookie = config.get_cookies()
        if not cookie:
            return {
                "is_valid": False,
                "message": "未设置Cookie"
            }
        
        async with aiohttp.ClientSession() as session:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Cookie': cookie
            }
            async with session.get('https://api.bilibili.com/x/web-interface/nav', headers=headers) as response:
                if response.status != 200:
                    return {
                        "is_valid": False,
                        "message": "Cookie无效"
                    }
                
                data = await response.json()
                if data['code'] != 0:
                    return {
                        "is_valid": False,
                        "message": "Cookie无效"
                    }
                
                user_info = data['data']
                if not user_info['isLogin']:
                    return {
                        "is_valid": False,
                        "message": "Cookie已失效"
                    }
                
                return {
                    "is_valid": True,
                    "user_info": {
                        "username": user_info['uname'],
                        "uid": user_info['mid']
                    }
                }
    except Exception as e:
        return {
            "is_valid": False,
            "message": f"检查Cookie状态失败: {str(e)}"
        }

def save_cookie(cookie: str) -> None:
    """
    保存cookie到配置文件
    
    参数：
        cookie (str): 要保存的cookie字符串
    """
    config = Config()
    config.save_cookies(cookie)

def get_cookie() -> str:
    """
    从配置文件获取cookie
    
    返回：
        str: 保存的cookie字符串，如果不存在则返回空字符串
    """
    config = Config()
    return config.get_cookies()

def set_test_invalid_cookie():
    """设置测试用的无效cookie"""
    try:
        config = Config()
        # 保存一个无效的cookie
        invalid_cookie = "SESSDATA=invalid;bili_jct=invalid;DedeUserID=invalid"
        config.save_cookies(invalid_cookie)
        return True
    except Exception as e:
        raise ValueError(f"设置测试Cookie失败: {str(e)}")

async def verify_and_save_cookie(cookie: str) -> dict:
    """
    验证并保存cookie
    
    参数：
        cookie (str): 用户提供的cookie字符串
        
    返回：
        dict: 包含验证结果和用户信息的字典
    """
    try:
        # 验证cookie
        result = await verify_cookie(cookie)
        # 保存cookie
        save_cookie(cookie)
        return result
    except HTTPException as e:
        return {
            "status": "error",
            "error": e.detail
        } 